package com.yu.filter;


import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.json.JSONUtil;
import com.yu.model.entity.User;
import com.yu.model.pojo.Result;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("拦截到 {}",request.getRequestURI());
        String requestURI = request.getRequestURI();
        String[] noAsk=new String[]{
                "/student/login",
                "/student/logout",
                "teacher/login",
                "teacher/logout"
        };
        for (String path : noAsk) {
            boolean match = PATH_MATCHER.match(requestURI, path);
            if(match){
                log.info("拦截到 {} 不需要处理",request.getRequestURI());
                filterChain.doFilter(request,response);
                return;
            }
        }

        User student = (User) request.getSession().getAttribute("student");
        if(student!=null){
            filterChain.doFilter(request,response);
            return;
        }
        response.getWriter().write(JSONUtil.toJsonStr(Result.error("NOT_LOGIN")));
        return;
    }
}
